<?php
/**
 * Контроллер категорий
 * 
 * Управление категориями
 * @author Anton Zavidov
 * @package myLiveShop
 */

/**
 * Класс контроллера для управления категориями
 *
 */
class ControllerCategory extends Element{
	/**
	 * Констуктор
	 *
	 * @param string $className имя контроллера
	 */
	public function __construct($className=null){
		$this->name='category';
		parent::__construct($className?$className:__CLASS__);
	}
	/**
	 * Просмотр елемента
	 *
	 */
	public function show(){
		parent::show();
		$this->view->set(
			'list',
			$this->model()->load(
				false,
				array(
					ModelCategory::F_CATEGORY_ID,
					ModelCategory::F_TITLE,
					ModelCategory::F_PARENT_ID,
				)
			)
		);
        $this->build();
	}
	/**
	 * Просмотр елемента
	 *
	 */
	public function display(){
		parent::display(true);
		$params = array();
		$model = Requestlocal::getString(ModelCategory::F_MODEL);
		if($model)$params['where'] = ModelCategory::F_MODEL.'="'.$model.'"';
		$element = $this->model()->loadOne($this->id,false,$params);
		$element['parent_name'] = $element['parent_id'] ? $this->model()->loadOne($element['parent_id'], array(ModelCategory::F_TITLE)) : '';
		$element['shop'] = $this->model('shop')->getName($element[ModelCategory::F_SHOP_ID]);
		$this->view->set('element',$element);
		$this->build();
	}
	/**
	 * Форма редактирования
	 *
	 */
	public function edit(){
		parent::edit(true);
		if(!Core::mustLogin()) return;
		$this->view->set('element',$this->model()->loadOne($this->id,array(
		  ModelCategory::F_CATEGORY_ID,
		  ModelCategory::F_TITLE,
		  ModelCategory::F_DESCRIPTION,
		  ModelCategory::F_PUBLISH,
		  ModelCategory::F_MODEL
		)));
		$this->build();
	}
	/**
	 * Форма создания
	 *
	 */
	public function add(){
		parent::add();
		Core::mustLogin();
		$this->build();
	}
	/**
	 * Создание
	 *
	 */
	public function save(){
		parent::save();
		if(!Core::mustLogin()) return false;
		$category_id = Requestlocal::getInt(ModelCategory::F_CATEGORY_ID,null,'post');
		$isNew = $category_id == null;
		$shop_id = $this->model('shop')->getId(Requestlocal::getString('shop', ''));
		$result=$this->model()->save(
			array(
				ModelCategory::F_TITLE=>Requestlocal::getString(ModelCategory::F_TITLE),
				ModelCategory::F_DESCRIPTION =>Requestlocal::getString(ModelCategory::F_DESCRIPTION),
				ModelCategory::F_PARENT_ID =>0,
				ModelCategory::F_MODEL =>Requestlocal::getString(ModelCategory::F_MODEL),
				ModelCategory::F_SHOP_ID =>$shop_id,
				ModelCategory::F_PUBLISH =>Core::setAccess()
			),
			$category_id
		);
        if(is_numeric($result)){
            $category_id = $result;
        }
        if(is_array($result)){
        	$this->view->result($result);
        } else {
        	//сохраняем параметры
        	$params = array();
        	$c = 0;
        	$this->model('param');
        	while (Requestlocal::getString("paramType_".$c, "") != "") {
        		$el = array(
        			ModelParam::F_TITLE => Requestlocal::getString("paramName_".$c),
        			ModelParam::F_VALUES => Requestlocal::getString("paramValue_".$c),
        			ModelParam::F_DESCRIPTION => Requestlocal::getString("paramDescription_".$c),
        			ModelParam::F_TYPE => (int) Requestlocal::getInt("paramType_".$c),
        			ModelParam::F_SORT => $c,
        			ModelParam::F_CATEGORY_ID => (int) $category_id,
        			ModelParam::F_TO_ORDER => 0 ///надо не забыть поменять, это флаг отправлять этот параметр в заказ или нет
        		);
        		if($element = Requestlocal::getInt("paramId_".$c,0)){
        			$el[ModelParam::F_PARAM_ID] = (int) $element;
        		}
        		$params[] = $el;
        		$c++;
        	}
        	import('controller.param',true)->saveForCategory($category_id, $params, $isNew);
        	$this->view->result(false);
        }
	}
	/**
	 * Удаление
	 *
	 */
	public function delete(){
		if(!Core::mustLogin()) return false;
		parent::delete(false);
		$this->findId(true);
		if($this->id){
            $this->model()->deleteRecursive($this->id,ModelCategory::F_PARENT_ID);
            if(Core::isJSON()) {
                $this->view->result();
                return true;
            }
        }elseif(Core::isJSON()) {
            $this->view->result(true);
            return false;
        }
		Core::redirect(base64_decode(Vars::_(Core::REFERER)),T::_('Deleted'));
	}

    /**
     * Получаем список категорий по типу и пользователю
     *
     * @param strimg $model тип
     * @param int $id id пользователя или ничего, если все (если 0 то текущего)
     * @return array
     */
	public function JSONList(){
        if(!Core::isJSON()) return false;
		$model = Requestlocal::getVar('model',false);
		$id = Requestlocal::getInt('id',0);
		$shop = Requestlocal::getInt('shop',null);
		if(!$shop){
			$shop = Requestlocal::getString('shop_name',null);
			if($shop) $shop = $this->model('shop')->getId($shop);
		}
		$data = $this->getList($model, $shop, $id, Requestlocal::getInt('tree',1)==1);
		$this->view->setAll(Requestlocal::getInt('asTable',null) ? $this->view->tablePack($data) : $data);
	}

    /**
     * Получаем список категорий по типу и пользователю
     *
     * @param strimg $model тип
     * @param int $id id пользователя или ничего, если все (если 0 то текущего)
     * @return array
     */
	public function getList($model, $id=null, $parent=0, $forTree = false){
		$params = array();
		if($model) $params[] = ModelCategory::F_MODEL.'="'.$model.'"';
	    if($id !== null){
	        //для определённого магазина
	        $params[]=ModelCategory::F_SHOP_ID.'='.B($id);
	    }else{
	        //для текущего магазина

	        ///НАДО СДЕЛАТЬ <-----
	    }
	    $list=$this->model()->load(false,array(ModelCategory::F_CATEGORY_ID,ModelCategory::F_TITLE,ModelCategory::F_PARENT_ID,ModelCategory::F_DESCRIPTION, ModelCategory::F_COUNT_ELEMENTS, ModelCategory::F_PUBLISH),(count($params) ? 
		    array(
		       'where'=>implode(' AND ', $params)
		    ) : 
		    array()
	    ));
	    $return=array();
	    if(is_array($list)){
	        if($forTree)
                $return=$this->getParentTree($list,$parent);
            else
                $return=$this->getParent($list,$parent);
	    }
	    return $return;
	}
    private function getParentTree(&$list, $id, $level=0){
        $return=array();
        foreach ($list as $item) {
            if($item[ModelCategory::F_PARENT_ID]==$id){
                if ($level==Requestlocal::getInt('maxLevel',2)) {
                    return true;
                } else {
                    $res = array(
                        'category_id' => $item['category_id'],
                        'text' => $item['title'],
                        'description' => $item['description'],
                        'count_elements' => $item['count_elements'],
                        'publish' => $item['publish']
                    );
                    if ($level==1){
                        $res['hasChildren'] = $this->getParentTree($list,$item[ModelCategory::F_CATEGORY_ID], $level+1);
                    } else {
                        $res['children'] = $this->getParentTree($list,$item[ModelCategory::F_CATEGORY_ID], $level+1);
                    }
                    $return[]=$res;
                }
            }
        }
        if(!count($return))return false;
        return $return;
    }
	private function getParent(&$list,$id){
        $return=array();
        foreach ($list as $item) {
            if($item[ModelCategory::F_PARENT_ID]==$id){
                $item['child']=$this->getParent($list,$item[ModelCategory::F_CATEGORY_ID]);
                $return[$item[ModelCategory::F_CATEGORY_ID]]=$item;
            }
        }
        if(!count($return))return false;
        return $return;
    }
    //жуткий костыль поиска полного пути
    public function backStep($id = null, $list = false){
    	if($id === null){
    		$id = Requestlocal::getInt('id',0);
    		$list = array();
    	}
    	if($id > 0){
    		$data = $this->model()->loadOne($id,array(ModelCategory::F_CATEGORY_ID, ModelCategory::F_PARENT_ID, ModelCategory::F_TITLE));
    		$list[] = $data;
    		$this->backStep($data[ModelCategory::F_PARENT_ID], $list);
    	}else{
    		$this->view->set('list',array_reverse($list));
    	}
    }
}